<template>
  <div class="comment">
    <header class="header">
      <h1 class="title">发表评论</h1>
    </header>
    <textarea class="content" name="" id="" cols="30" rows="10" v-model="content" placeholder="请输入你bb的内容"> </textarea>
    <van-button type="danger" block @click="postComment">
      提交
    </van-button>
    <ul class="comment-list">
      <li v-for="(item, index) in comments" :key="index">
        <header>
          <span>第{{ (index += 1) }}楼</span>
          <span>{{ item.user_name }}</span>
          <span>{{ item.add_time }}</span>
        </header>
        <p>{{ item.content }}</p>
      </li>
    </ul>
    <van-button type="danger" block @click="getMore">
      {{ hasMoreText }}
    </van-button>
  </div>
</template>
<script>
export default {
  props: ['id'],
  data: () => ({
    page: 1,
    pageSize: 3,
    comments: [],
    hasMore: false,
    content: ''
  }),
  created() {
    this.getComments()
  },
  methods: {
    async getComments() {
      if (this.hasMore !== false) return
      this.page++
      try {
        const {
          data: { message, count }
        } = await this.Api.getComments({ id: this.id, page: this.page, pageSize: this.pageSize })
        this.comments = this.comments.concat(message)
        console.log(count)
        this.hasMore = this.page * this.pageSize > count
        console.log(this.hasMore)
      } catch (error) {
        this.$Toast('请求评论数据失败')
      }
    },
    async postComment() {
      try {
        const {
          data: { message }
        } = await this.Api.postComment({ id: this.id, content: this.content })
        console.log(message)
        this.comments.unshift({
          add_time: new Date().getTime(),
          content: this.content,
          id: new Date().getTime(),
          user_name: '匿名用户'
        })
      } catch (error) {
        this.$Toast('添加评论数据失败')
      }
    },
    getMore() {
      this.getComments()
    }
  },
  computed: {
    hasMoreText() {
      return this.hasMore ? '被掏空了' : '加载更多'
    }
  }
}
</script>
<style lang="less" scoped>
.comment {
  .header {
    border-bottom: 1px solid #ddd;
    margin-bottom: 10px;
    .title {
      font-size: 20px;
    }
  }
  .content {
    width: 98%;
  }
  .comment-list {
    header {
      border-bottom: 1px solid #ddd;
      padding: 4px 0;
      span {
        margin-right: 4px;
      }
    }
  }
}
</style>
